package com.xcity.game.activity2.share;

import com.xcity.db.entity.Activity;
import com.xcity.db.entity.Player;
import com.xcity.db.entity.User;
import com.xcity.game.activity2.ActivityImpl;
import com.xcity.game.activity2.share.template.QQShareActivityTemplate;
import com.xcity.game.common.MessageConst;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.request.Share2Request;
import com.xcity.pomelo.response.HintResponse;
import com.xcity.pomelo.response.Share2Response;

import gnu.trove.map.TIntObjectMap;
import naga.x.App;
import naga.x.event.Event;
import naga.x.event.EventListener;
import naga.x.game.template.TemplateService;
import naga.x.net.Session;
import naga.x.net.annotation.OPHandler;
import naga.x.net.impl.pomelo.annotation.PomeloOP;
import naga.x.service.ServiceException;

/**
 * 分享活动<br/>
 * 微博：分享微博<br/>
 * QQ、玩吧：分享说说<br/>
 * @author yang.li
 *
 */
@OPHandler
public class ShareActivity extends ActivityImpl implements EventListener {

	private EventListener eventDispatcher;
	private TIntObjectMap<QQShareActivityTemplate> templatesMap;
	
	public ShareActivity(Activity entity) {
		super(entity);
		eventDispatcher = new EventDispatcher();
		templatesMap = App.getApp().getServiceManager().get(TemplateService.class).getTemplates(QQShareActivityTemplate.class);
	}

	@Override
	public String getId() {
		return getClass().getName();
	}

	@Override
	public void init() {
	}

	@Override
	public void save() {
	}

	@Override
	public void startup() throws ServiceException {
		App.getApp().getEventManager().register(this);
	}

	@Override
	public void shutdown() throws ServiceException {
		App.getApp().getEventManager().unRegister(this);
	}

	@Override
	public boolean update() {
		return true;
	}

	@Override
	public void setDirty() {
	}

	@Override
	public int[] getEventTypes() {
		return eventDispatcher.getEventTypes();
	}

	@Override
	public void handleEvent(Event event) {
		eventDispatcher.handleEvent(event);
	}
	
	public QQShareActivityTemplate findTemplate(int id) {
		return templatesMap.get(id);
	}
	
	@PomeloOP(PomeloRoute.SHARE_GAME2)
	protected void doShare(Session session, Share2Request req) {
		Player player = session.getClient();
		User acc = player.getAccount();
		ShareAction action = ShareActionFactory.create(acc.getChannel());
		if (action == null) {
			session.send(new HintResponse(req.getSerial(), MessageConst.SHARE_NOT_ALLOWED));
			return;
		}
		try {
			Share2Response res = req.type != 1 ? action.share(player, req) : action.reward(player, req);
			session.send(res);
		} catch (ShareException e) {
			session.send(new HintResponse(req.getSerial(), e.getMessage()));
		}
	}

}
